package com.hpf.community.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hpf.community.annotations.MonitorLog;
import com.hpf.community.constants.CommunityConstants;
import com.hpf.community.enums.LogEnum;
import com.hpf.community.model.CommunityModel;
import com.hpf.community.model.UserModel;
import com.hpf.community.service.ICommunityService;
import com.hpf.community.service.IUserService;
import com.hpf.community.utils.CommonUtils;
import com.hpf.community.utils.PaginationResult;
import com.hpf.community.utils.StandardResult;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 *　　
 *   Community 控制器    社团表
 *
 *   @author huangpengfei
 *   @since 2020-04-04
 */

@RestController
public class CommunityController {
    private final Logger logger = LoggerFactory.getLogger(CommunityController.class);

    @Autowired
    public ICommunityService communityService;

    @Autowired
    public IUserService userService;

    /**
     * 获取分页列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/community")
    @RequiresRoles("3")
    public StandardResult selectPage(@ModelAttribute CommunityModel communityModel,
                                     @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                     @RequestParam(value = "pageNumber",required = false)Integer pageNumber,
                                     @RequestParam(value = "searchKey",required = false)String searchKey,
                                     Date startTime,
                                     Date endTime) {
		try {
			if (pageSize == null || pageNumber == null) {
				return StandardResult.faildCheck("缺少必要的分页参数！");
			}
	     	Page<CommunityModel> page = new Page<>(pageNumber, pageSize);
            Wrapper<CommunityModel> wrapper = new EntityWrapper<CommunityModel>();
			if(StringUtils.isNotBlank(searchKey)){
			    wrapper.like(CommunityModel.NAME,searchKey);
			    wrapper.or();
			    wrapper.like(CommunityModel.DESCRIPTION,searchKey);
			    wrapper.or();
			    wrapper.like(CommunityModel.GUIDE_TEACHER,searchKey);
			    wrapper.or();
			    wrapper.like(CommunityModel.FACULTY,searchKey);
			}
			if(StringUtils.isNotBlank(communityModel.getStatus())){
			    wrapper.andNew();
			    wrapper.eq(CommunityModel.STATUS,communityModel.getStatus());
			}
			if(StringUtils.isNotBlank(communityModel.getLv())){
			    wrapper.andNew();
			    wrapper.eq(CommunityModel.LV,communityModel.getLv());
			}
            if(StringUtils.isNotBlank(communityModel.getType())){
                wrapper.andNew();
                wrapper.eq(CommunityModel.TYPE,communityModel.getType());
            }
            if(null != startTime){
                wrapper.andNew();
                wrapper.ge(CommunityModel.CREATE_DATETIME,startTime);
            }
            if(null != endTime){
                wrapper.andNew();
                wrapper.le(CommunityModel.CREATE_DATETIME,endTime);
            }
			wrapper.eq(CommunityModel.IS_DELETE, CommunityConstants.USER_STATUS_ZC);
			wrapper.orderBy(CommunityModel.CREATE_DATETIME,false);
            communityService.selectPage(page, wrapper);
            return PaginationResult.ok(null, page.getRecords(), page.getTotal(), page.getPages());
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return PaginationResult.faild(e);
		}
    }

	/**
     * 获取社团列表
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/communityList")
    public StandardResult selectList(@ModelAttribute CommunityModel communityModel) {
		try {
			Wrapper<CommunityModel> wrapper = new EntityWrapper<CommunityModel>();
			wrapper.setSqlSelect("ID AS id,NAME AS name");
			wrapper.eq(CommunityModel.IS_DELETE,CommunityConstants.USER_STATUS_ZC);
			wrapper.eq(CommunityModel.STATUS,CommunityConstants.USER_STATUS_ZC);
			return StandardResult.ok(null, communityService.selectList(wrapper));
		} catch (Exception e) {
			logger.error("异常信息:", e);
			return StandardResult.faild(e);
		}
    }


     /**
      * 添加社团
      *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PostMapping("/community")
    @RequiresRoles("3")
    @MonitorLog(value = "添加社团",operateType = LogEnum.INSERT)
    public StandardResult insert(@ModelAttribute CommunityModel communityModel) {
		try {
		    if(StringUtils.isBlank(communityModel.getId())){
                communityModel.setId(CommonUtils.getUUID());
		    }
		    communityModel.setCreateUserid(CommonUtils.getCurrentUser().getId());
            if(null == communityModel.getCreateDatetime()){
                communityModel.setCreateDatetime(new Date());
            }
            communityService.insertOrUpdate(communityModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
     * 修改，禁用社团
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @PutMapping("/community")
    @RequiresRoles("3")
    @MonitorLog(value = "修改社团信息、禁用社团或启用社团，具体看详细日志",operateType = LogEnum.UPDATE)
    public StandardResult updateById(@RequestBody CommunityModel communityModel) {
        try {
            if(StringUtils.isNotBlank(communityModel.getStatus())){
                if(StringUtils.equals(communityModel.getStatus(),CommunityConstants.USER_STATUS_JY)){
                    //禁用了社团，其后台的所有用户不能登录系统
                    Wrapper<UserModel> wrapper = new EntityWrapper<>();
                    wrapper.eq(UserModel.COM_ID,communityModel.getId());
                    wrapper.eq(UserModel.ROLE,CommunityConstants.USER_ROLE_HTYH);
                    wrapper.eq(UserModel.STATUS,CommunityConstants.USER_STATUS_ZC);
                    List<UserModel> userModels = userService.selectList(wrapper);
                    if(!userModels.isEmpty()){
                        userModels.stream().forEach(user -> {
                            user.setStatus(CommunityConstants.USER_STATUS_JY);
                        });
                        userService.updateBatchById(userModels);
                    }
                }
            }
            communityModel.setModifyUserid(CommonUtils.getCurrentUserId());
            communityModel.setModifyDatetime(new Date());
            communityService.updateById(communityModel);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }

    /**
        * 通过id获取详情
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @GetMapping("/community/{id}")
    public StandardResult selectById(@PathVariable String id) {
		try {
		     return StandardResult.ok(communityService.selectById(id));
		} catch (Exception e) {
		     logger.error("异常信息:", e);
		     return StandardResult.faild(e);
		}
    }

    /**
     * 删除数据，改状态
     *
     * @author : huangpengfei
     * @since : Create in 2020-04-04
     */
    @DeleteMapping("/community/{id}")
    @RequiresRoles("3")
    @MonitorLog(value = "删除社团操作",operateType = LogEnum.DELETE)
    public StandardResult deleteById(@PathVariable String id) {
        try {
            CommunityModel model = communityService.selectById(id);
            model.setModifyUserid(CommonUtils.getCurrentUserId());
            model.setModifyDatetime(new Date());
            model.setIsDelete(CommunityConstants.USER_STATUS_JY);
            communityService.updateById(model);
            return StandardResult.ok();
        } catch (Exception e) {
            logger.error("异常信息:", e);
            return StandardResult.faild(e);
        }
    }
}
